package com.zhx.sweet.handler;

import com.zhx.sweet.exception.SecurityLoginAuthenticationException;
import com.zhx.sweet.validate.code.ValidateCodeException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhanghaixuan
 * @create 2018/4/18-上午11:17
 **/
public class DefaultCuestomAuthentionFailedHandler implements CuestomAuthentionFailedHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        httpServletResponse.setContentType("application/json,charset=UTF-8");
        String message = "";

        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            message = "用户名或者密码错误!";
        } else if (e instanceof SecurityLoginAuthenticationException) {
            message = e.getMessage();

            if (StringUtils.isEmpty(message)) {
                message = "用户名或者密码错误!";
            }
        } else if (e instanceof ValidateCodeException) {
            message = e.getMessage();
        }

        httpServletResponse.getWriter().write("\"" + message + "\"");
    }
}
